package com.limao.servlet;

import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.limao.AsyncListener.AppAsyncListener;
import com.limao.Model.RecvData;
import com.limao.Utils.OutPrintClass;

@WebServlet(name="PlugServlet", urlPatterns="/PlugServlet",asyncSupported=true)
public class PlugServlet extends HttpServlet {

	private static final long serialVersionUID = 456860622544816761L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
		request.setCharacterEncoding("UTF-8");

			// 得到数据
			String StrData = OutPrintClass.readJSONString(request);

			if (StrData == null) {
				OutPrintClass.sendError(response, null,-1, "出错，无数据");
				return ;
			}
			RecvData DataObj = JSON.parseObject(StrData, RecvData.class);
			if (DataObj == null) {
				OutPrintClass.sendError(response, null, -1, "json解释出错");
				return ;
			}
		  
	      //开始异步调用，获取对应的AsyncContext。
	      AsyncContext asyncContext = request.startAsync();
	      //设置当前异步调用对应的监听器
	      asyncContext.addListener(new AppAsyncListener(DataObj));
	      //设置超时时间，当超时之后程序会尝试重新执行异步任务，即我们新起的线程。
	      asyncContext.setTimeout(15*1000L);
	      //新起线程开始异步调用，start方法不是阻塞式的，它会新起一个线程来启动Runnable接口，之后主程序会继续执行
	      ThreadPoolExecutor executor = (ThreadPoolExecutor) request.getServletContext().getAttribute("executor");
 	      executor.execute(new PlugAsyncProcessor(asyncContext, request,response,DataObj));
 	     
	}


}
